<?php
/* ========================================
 * --------------------
 *  Result.php
 * --------------------
 * Created on 29.03.2010
 * ========================================
 * $Revision: $
 * $Author: Dmitry Boycov
 * $HeadURL: $ 
 * $Id: $
 * ========================================
 * Changes ["date: description (who)"]:
 *
 * 29.03.2010: Original version (WHo)
 * 17:28:50: Time 
 */
require_once("app/App.php");

class Result{

	private $error = null;
	private $data = null;
	private $count = 0; // number of processed records
	//private $row_id = null

	/**
	 * construct
	 * @param  $res - result of sql query
	 * @return void
	 */
	public function __construct($res){
		if(!is_null($res)){
			if(!$this->checkError()){
				if(is_bool($res) === true){
					if($res){ // query update or insert
						$this->count = mysql_affected_rows();
					}else{
						$this->error = "MySQL error.Empty result";
					}
				}else{// query select
					$this->count = mysql_num_rows($res);
					$this->data = $this->fetchByAssoc($res);
					mysql_free_result($result);
				}
			}
		}else{
			$this->error = "MySQL error.Empty result";
		}
	}

	public function error(){
		return $this->error;
	}

	public function data(){
		return $this->data;
	}

	public function count(){
		return $this->count;
	}

	/**
	 * @access private
	 * @param  $result - result of sql query
	 * @return array
	 */
	private function fetchByAssoc($result){
		if(is_null($result)) return null;
		$ar = array();
		$settings = App::settings();
		while ($row = mysql_fetch_assoc($result)){
			$buf = array();
			foreach ($row as $key => $value){
				$buf[$key] = mb_convert_encoding($value,$settings['clientCharset'],$settings['db']['charset']);
			}
			$ar[] = $buf;
		}
        return $ar;
    }

	/**
	 * @access private
 	 * @return boolean true - error; false - no error
	 */
	private function checkError(){
        if (mysql_errno()){
            $this->error = "MySQL error ".mysql_errno().": ".mysql_error();
            return true;
        }
        return false;
    }
}
?>